import { _decorator, Node } from 'cc';
import { GameCore } from '../../Base/Class';
import { Constructor, NewClass, setClassName } from '../../Base/Global';
import { Singleton } from '../../Base/Singleton';
import { UIBase } from "./UIBase";
import { UIComponent } from "./UIComponent";
import { UIComponentProxy } from './UIComponentProxy';

/*
主要是对proxy进行管理- 负责proxy的创建和销毁
proxy真正的生成还是在UIComponentMananger中
*/

export class UIComponentCreateFactor extends GameCore.ClassBase
{
    private oBaseUI : UIBase = null;
    public get baseUI() : UIBase { return this.oBaseUI;}
    public set baseUI(oBaseUI : UIBase) { this.oBaseUI = oBaseUI;}
    public componentProxyList : Array<UIComponentProxy> = new Array<UIComponentProxy>();
    private lockDesotyProxy : number = 0;
    public CreateComponentProxy<T extends UIComponent>(classConstructor : Constructor<T>, oParent : Node, oComponentNode? : Node) : UIComponentProxy
    {
        // 向UIComponentMgr请求创建
        var proxy = NewClass(UIComponentProxy);
        this.componentProxyList.push(proxy);
        proxy.Init(classConstructor, oParent, this, oComponentNode);
        return proxy;
    }

    public CheckDestroyingProxyIsThis(proxy: UIComponentProxy) 
    {
        return this.lockDesotyProxy == proxy.instanceId;
    }

    public DestroyProxy(oUIComponentProxy : UIComponentProxy)
    {
        this.lockDesotyProxy = oUIComponentProxy.instanceId;
        var index = this.componentProxyList.indexOf(oUIComponentProxy);
        if(index >= 0)
        {
            this.componentProxyList.slice(index, 1);
        }
        oUIComponentProxy.Destory();
        this.lockDesotyProxy = 0;
    }

    public DestroyAllComponent()
    {
        while(this.componentProxyList.length > 0)
        {
            var proxy = this.componentProxyList.shift();
            this.DestroyProxy(proxy);
        }
    }
}

setClassName(UIComponentCreateFactor, "UIComponentCreateFactor")